/**
 * Created by hsia on 2017/4/24.
 */
var monit={},orgs=new Array(),countAdd=0;
var tips = true;
var nowunix = Math.round(new Date().getTime());//获取当前时间时间戳
var date = new Date();
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
var secunix = Math.round(date.getTime());
//setTimeout('autofresh()',secunix-nowunix);
setTimeout('autofresh()',3000);
function autofresh() {
    tips=false;//重加载不弹socket成功弹窗
    var html='<div class="collectFee" style="height:156px">'
        +'    <div class="total" id="total">'
        +'    </div>'
        +'    <div class="slider1 policeBox" id="policeBox">'
        +'    </div>'
        +'</div>'
        +'<div class="chargingMonitor" style="height:calc(100% - 168px);">'
        +'   <div class="tableDiv" style="width:600px;float:left;height:100%;overflow-y:auto;" data-bind="source: chargingGrid" id="tableDiv">'
        +'   </div>'
        +'   <div class="aisleFrame" id="aisleFrame" style="height:100%;overflow-y:auto;">'
        +'    </div>'
        +'</div>'
    $('#ChargeMonitDiv').empty();
    $('#ChargeMonitDiv').append(html);
    chargeMonit = new ChargeMonit($('#ChargeMonitDiv'));
    nowunix = Math.round(new Date().getTime());//获取当前时间时间戳
    setTimeout('autofresh()',secunix-nowunix);
    //setTimeout('autofresh()',6000);
}
var ChargeMonit = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
ChargeMonit.prototype={
    init:function () {

        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
        bindFieldArray.push({fieldName:"chargingGrid",defaultValue:[]});
        var bindFunctionArray = [
            {fName:"viewInfo",fs:this.showDetails},
        ];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.initHtml();
        this.initMonit();
        Utils.keepsession();//设置session永不过期
        if(tips){
            this.webS = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, this.targetObj);
        }
    },
    initHtml:function(){
        var that = this;
        that.targetObj.find('#tableDiv').kendoGrid({
            //height: 640,
            scrollable: true,
            sortable: true,
            filterable: false,
            pageable:false,
            columns: [
                { field: "identifier", title: "通行证号", width: "25%" },
                { field: "vehicleNo", title: "车牌号", width: "25%" },
                { field: "otime", title: "通行时间", width: "30%" },
                { command: { text: "查看抓拍", click: function(e){
                    e.preventDefault();
                    var tr = $(e.target).closest("tr");
                    var data = this.dataItem(tr);

                    JsonpAjax(baseApiPath+"recordMarket/" + data.rid,null,"json",function(result){

                        window.showInoutRecodeView=result;
                        that.editDiv = that.sysUtils.openWindow(that.editDiv,{
                            title:'查看进出详情',
                            height:"680px",
                            width:"940px",
                            resizable:true,
                            content:"views/parkLotCenter/recordMarket/inoutRecoderEdit.html"
                        }, true);
                    });

                } }, title: "操作", width: "20%" }
            ]
        });
    },
    //渲染页面
    initMonit:function (e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        JsonpAjax(baseApiPath+"centralized/chargeMonit",null,"json",function(result){
            that.orgs = result.orgs;
            if(result){
                var pathName = result.orgs[0].pathName;
                var basic = new Array();
                monit['parkName'] = pathName.substring(0,pathName.indexOf(','));
                monit['code'] = result.orgs[0].code;
                monit['today'] = result.orgs[0].today;
                monit['parkCount'] = result.orgs[0].parkCount;
                basic.push(monit);
                orgs=result.orgs;
                var wsnCharges=new Array();
                countAdd=result.orgs[0].parkCount;
                var totalHtml='<ul>'
                    +'    <li>'+pathName.substring(0,pathName.indexOf(','))+'</li>'
                    +'    <li>日期：'+result.orgs[0].today+'</li>'
                    +'    <li>岗亭收费：<i class="fontRed" id="parkId">'+result.orgs[0].parkCount+'</i>&nbsp;元</li>'
                    +'</ul>';

                //岗亭收费显示区域
                var policeBoxHtml ='';
                that.targetObj.find("#total").append(totalHtml);
                for(var i=0,l=result.orgs.length;i <l;i++){
                    if('wsn'==result.orgs[i].type){
                        var name = result.orgs[i].pathName;
                        var wsnCharge={};
                        name = name.substring(name.indexOf(',')+1,name.length).replaceAll(',','—');
                        wsnCharge['name']=name;
                        wsnCharge['onDuty']='';
                        wsnCharge['wsnCount'] = result.orgs[i].wsnCount;
                        wsnCharge['code'] = result.orgs[i].code;
                        wsnCharges.push(wsnCharge);
                        policeBoxHtml+='<div class="slide">'
                            +'    <div class="list">'
                            +'        <strong>'+name+'</strong>'
                            +'        <p>当班人员：</p>'
                            +'        <p>收费金额：<i class="fontRed" name="'+result.orgs[i].code+'">'+result.orgs[i].wsnCount+'</i>&nbsp;元</p>'
                            +'    </div>'
                            +'</div>';

                    }
                }
                //工作站收费显示区域
                that.targetObj.find("#policeBox").append(policeBoxHtml);
                that.targetObj.find('.slider1').bxSlider({
                    slideWidth: 275,
                    minSlides: 6,
                    maxSlides: 6,
                    useCSS:false,
                    tickerHover: true,
                    ticker: true,
                    speed: 20000,
                    startSlides: 0,
                    slideMargin: 10
                });
                //出场记录列表区域
                var wsnRecodes=new Array(),subRecodes=new Array();
                var aisleFrameHtml = '';//抓拍图片html
                for(var i=0,l=result.recs.length;i <l;i++){
                    var name = result.recs[i].pathName;
                    var wsnRecode={};
                    name = name.substring(name.indexOf(',')+1,name.length).replaceAll(',','-');
                    wsnRecode['name']=name;
                    wsnRecode['url']=result.recs[i].url == undefined ? '' : result.recs[i].url;
                    wsnRecode['otime']=result.recs[i].otime == undefined ? '' : result.recs[i].otime;
                    wsnRecode['rid']=result.recs[i].rid;
                    wsnRecode['identifier']=result.recs[i].identifier;
                    wsnRecode['vehicleNo']=result.recs[i].vehicleNo;
                    wsnRecode['chnCode']=result.recs[i].chnCode;
                    wsnRecode['wsnCode']=result.recs[i].wsnCode;
                    wsnRecode['payMoney']=result.recs[i].payMoney == undefined ? 0 : result.recs[i].payMoney;
                    if(i<4){
                        subRecodes.push(wsnRecode);

                        aisleFrameHtml+='<div class="aisleList">'
                            +'    <div class="name">'+name+'</div>'
                            +'    <div class="frame"><img src="'+((result.recs[i].url == undefined) ? "images/404-bg.png" : result.recs[i].url) +'" /></div>'
                            +'    <div class="info">'
                            +'        <ul>'
                            +'            <li>通行证号：'+result.recs[i].identifier+'</li>'
                            +'            <li>车牌号：'+result.recs[i].vehicleNo+'</li>'
                            +'            <li>通行时间：'+((result.recs[i].otime == undefined) ? "" : result.recs[i].otime)+'</li>'
                            +'            <li>收费金额：<i>'+((result.recs[i].payMoney == undefined) ? 0 : result.recs[i].payMoney)+'元</i></li>'
                            +'        </ul>'
                            +'    </div>'
                            +'</div>';
                    }
                    wsnRecodes.push(wsnRecode);
                }
                monit['wsnCharges'] = wsnCharges;
                monit['wsnRecodes'] = wsnRecodes;
                monit['subRecodes'] = subRecodes;

                that.sysUtils.mvvmModel.set("chargingGrid",monit.wsnRecodes);

                that.targetObj.find("#aisleFrame").append(aisleFrameHtml);

            }
        },false);
    },
    handlerMessage:function (e) {
        var info = JSON.parse(e.data);
        if('21'==info.msgType && info.data.length > 0){
            var wsnRecodes=new Array();
            for(var o=info.data.length-1;o>=0;o--){
                var wsnRecode={};
                var name;
                for(var i in orgs){
                    if(orgs[i].code ==info.data[o].outChannelCode){
                        name= orgs[i].pathName;
                        name= name.substring(name.indexOf(',')+1,name.length).replaceAll(',','-');
                    }
                }
                wsnRecode['name']=name;
                wsnRecode['url']=info.data[o].outImg[0].imgUrl == undefined ? 'images/404-bg.png' : info.data[o].outImg[0].imgUrl;
                wsnRecode['otime']=info.data[o].outTime == undefined ? '' : info.data[o].outTime;
                wsnRecode['rid']=info.data[o].id;
                wsnRecode['identifier']=info.data[o].uniqueIdentifier;
                wsnRecode['vehicleNo']=info.data[o].vehicleNo;
                wsnRecode['chnCode']=info.data[o].outChannelCode;
                wsnRecode['wsnCode']=info.data[o].outFieldCode;
                wsnRecode['payMoney']=info.data[o].chargeMoney == undefined ? 0 : info.data[o].chargeMoney;
                chargeMonit.targetObj.find('i[name="'+info.data[o].outFieldCode+'"]').each(function () {
                    var add = this.innerText;
                    $(this).text(parseInt(add)+parseInt(info.data[o].chargeMoney));
                });
                countAdd +=parseInt(info.data[o].chargeMoney);
                //列表显示区域
                var lenth = monit['wsnRecodes'].unshift(wsnRecode)-100;
                if(lenth>0){
                    monit['wsnRecodes'].prop();//删除最后一个
                }

                //图片显示区域
                var aisleFrameHtml = '<div class="aisleList">'
                    +'    <div class="name">'+name+'</div>'
                    +'    <div class="frame"><img src="'+((info.data[o].outImg[0].imgUrl == undefined) ? 'images/404-bg.png' : info.data[o].outImg[0].imgUrl) +'" /></div>'
                    +'    <div class="info">'
                    +'        <ul>'
                    +'            <li>通行证号：'+info.data[o].uniqueIdentifier+'</li>'
                    +'            <li>车牌号：'+info.data[o].vehicleNo+'</li>'
                    +'            <li>通行时间：'+((info.data[o].outTime == undefined) ? "" : info.data[o].outTime)+'</li>'
                    +'            <li>收费金额：<i>'+((info.data[o].chargeMoney == undefined) ? 0 : info.data[o].chargeMoney)+'元</i></li>'
                    +'        </ul>'
                    +'    </div>'
                    +'</div>';
                var das = chargeMonit.targetObj.find('.aisleList');
                for(var h in das){
                    if(h<3){
                        console.info(das[h].innerHTML);
                        aisleFrameHtml+='<div class="aisleList">'+das[h].innerHTML+'</div>';
                        console.info(aisleFrameHtml);
                    }
                }
                chargeMonit.targetObj.find('#aisleFrame').empty();
                chargeMonit.targetObj.find('#aisleFrame').append(aisleFrameHtml);
                wsnRecodes.push(wsnRecode);
            }
            chargeMonit.targetObj.find('#parkId').text(countAdd);
            //monit['wsnRecodes'].unshift(wsnRecodes);
            var subRecodes = new Array();
            for(var i=0;i<4;i++){
                subRecodes[i]=monit['wsnRecodes'][i];
            }
            monit['subRecodes'] = subRecodes;

            chargeMonit.sysUtils.mvvmModel.set("chargingGrid",monit.wsnRecodes);
        }
    },
    openSuccess : function(e) {
        //订阅出场通讯记录
        if(chargeMonit.orgs){
            var tps = new Array();
            for(var o in chargeMonit.orgs){
                if(chargeMonit.orgs[o].type=='chn_out'){
                    var topic = '/*/'+chargeMonit.orgs[o].code+'/IE/21';
                    tps.push(topic);
                }
            }
            chargeMonit.webS.registerTopics(tps);
        }

        //$.growlUI('通信开启', 'Have a nice day!');
        if(tips){
            layer.open({
                type: 1,
                //time:1500,
                title: false,
                shade: 0,
                offset: 'rb',
                //closeBtn: 0,
                shadeClose: false,
                area: ['300px', '200px'],
                skin: 'layui-layer-rim', //加上边框
                content: '<div class="layuiCon">岗亭连接成功,<br>开始接收岗亭收发数据...</div>'
            });
        }

    },
    onClose:function () {
        notification({title : "岗亭数据接收失败", message : "连接断开，请检查设备、网络是否正常,关闭页面再试"}, 'info');
    }
}
